#include <cstdio>
#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
#include "Mutex.hpp"
#include "Mutex.hpp"

int tickets = 1000;

// 锁
Mutex lock;

void *route(void *args)
{
    while (1)
    {
        {
            LockGuard lockguard(&lock);//RAII风格的加锁
            if (tickets > 0)
            {
                // 抢票
                usleep(10000);
                printf("%s 抢占票号：%d\n", (const char *)args, tickets--);
                lock.Unlock(); // 解锁
            }
            else
            {
                lock.Unlock();
                break;
            }
        }
    }
    return (void *)0;
}
int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, nullptr, route, (void *)"thread-1");
    pthread_create(&t2, nullptr, route, (void *)"thread-2");
    pthread_create(&t3, nullptr, route, (void *)"thread-3");
    pthread_create(&t4, nullptr, route, (void *)"thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
}